package cn.stronglink.assetmanage.business.check.view.sync;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.adapter.CheckListAdapter;
import cn.stronglink.assetmanage.business.check.adapter.CheckOrderAdapter;
import cn.stronglink.assetmanage.business.check.model.SyncModel;
import cn.stronglink.assetmanage.business.check.presenter.SyncListPresenter;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.index.base.BaseChildFragment;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.check.CheckService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 待同步表单列表
 */
public class CheckSyncListFragment extends BaseChildFragment implements ITaskSyncListener {
    private CheckListAdapter listAdapter;
    private SyncModel syncModel;
    private CheckSyncView checkSyncView;
    private SyncListPresenter syncListPresenter;
    //待同步表单列表
    private RecyclerView rv_checksync_order_list;
    private LinearLayoutManager layoutManager;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private Button btnCheckSync;
    private CheckService checkService;

    private Dialog mDialog;
    List<Check> checkList;
    private TaskSyncModel taskSyncModel;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_check_sync_list, container, false);
        initViewAndData(rootView);
        return rootView;
    }

    private void initViewAndData(View view) {
        try {
            checkList = new ArrayList<>();
            checkService = new CheckService();
            mDialog = CustomProgressDialog.createLoadingDialog(this.getContext(), "正在同步中...");
            mDialog.setCancelable(false);
            btnCheckSync = view.findViewById(R.id.btn_check_sync);
            txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
            txt_main_title.setText("验收入库");
            txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
            txt_title_right.setVisibility(View.INVISIBLE);
            txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
            txt_title_left.setVisibility(View.INVISIBLE);
            rv_checksync_order_list = view.findViewById(R.id.rv_checksync_order_list);
            listAdapter = new CheckListAdapter(getActivity());
            layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
            rv_checksync_order_list.setLayoutManager(layoutManager);
            rv_checksync_order_list.setAdapter(listAdapter);
            listAdapter.setOnItemClickListener(new onRecyclerListener() {
                @Override
                public void onItemClicked(View v, int postion) {
                    if (checkList != null && checkList.size() > 0) {
                        MainActivity activity = (MainActivity) getActivity();
                        PromissionEntity pe = new PromissionEntity();
                        pe.setFragment(new SyncAssetFragment());
                        pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
                        pe.setTitle("入库待同步");
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, checkList.get(postion).getId_());
                        pe.setBundle(bundle);
                        activity.onEventRegister(pe);
                    }
                }
            });
            syncModel = new SyncModel();
            checkSyncView = new CheckSyncView(this, view, listAdapter);
            syncListPresenter = new SyncListPresenter(checkSyncView, syncModel);
            taskSyncModel = new TaskSyncModel();
            taskSyncModel.setListener(this);
            btnCheckSync.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    syncCheckData();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.toastShort("没有数据显示");
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        try {
            if (isVisible) {
                refreshView();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void refreshView() {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (syncModel != null && checkSyncView != null) {
                        checkList = syncModel.getDataByOrderNoDistince();
                        checkSyncView.setListData(checkList);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void syncCheckData() {
        if (mDialog != null) {
            mDialog.show();
        }else{
            mDialog = CustomProgressDialog.createLoadingDialog(this.getContext(), "正在同步中...");
            mDialog.setCancelable(false);
            mDialog.show();
        }
        if (checkList != null && checkList.size() > 0) {
            try {
                taskSyncModel.uploadCheckList(checkList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtil.toastShort("同步失败"+e.getMessage());
    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtil.toastShort("同步成功");
        syncModel.deleteSyncData(checkList);
        //刷新ui显示
        refreshView();
    }
}
